import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit'
import { queryCounter } from '@/services/test.ts'

export interface CounterState {
  value: number
}

const initialState: CounterState = {
  value: 0
}

// 定义异步action
export const asyncChangeUserAgeAction = createAsyncThunk(
  'counter/asyncChange',
  async (_value: string) => {
    const res = await queryCounter()
    return res.data
  }
)


export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: (state: CounterState) => {
      state.value += 1
    },
    decrement: (state: CounterState) => {
      state.value -= 1
    },
    incrementByAmount: (state: CounterState, action: PayloadAction<number>) => {
      state.value += action.payload
    }
  },
  extraReducers: (builder) => {
    builder.addCase(asyncChangeUserAgeAction.fulfilled, (state, action) => {
      state.value = action.payload.counter
    })
  }
})

export const { increment, decrement, incrementByAmount } = counterSlice.actions
export default counterSlice.reducer
